(function(){
    var LPB = window.LPB = window.LPB || {plugins:[],
        genSource:function(){

            //#build是左边的富文本区域，将左边的内容生成到#source中
            var $temptxt = $("<div>").html($("#build").html());
            //scrubbbbbbb
            $($temptxt).find(".fix-component").attr({"title": null,
                "data-original-title":null,
                "data-type": null,
                "data-content": null,
                "rel": null,
                "trigger":null,
                "style": null});
            $($temptxt).find(".valtype").attr("data-valtype", null).removeClass("valtype");
            // $($temptxt).find(".fix-component").removeClass("component");
            $($temptxt).find("form").attr({"id":  null, "style": null});
            $("#source").val($temptxt.html().replace(/\n\ \ \ \ \ \ \ \ \ \ \ \ /g,"\n"));
        }
    };

    /* 表单名称控件 form_name
    acc  是 class="component" 的DIV
    e 是 class="leipiplugins" 的控件
    */
    LPB.plugins['form_name'] = function (active_component,leipiplugins) {
        var plugins = 'form_name',popover = $(".popover");
        //右弹form  初始化值
        $(popover).find("#orgvalue").val($(leipiplugins).val());
        //右弹form  取消控件
        $(popover).delegate(".btn-danger", "click", function(e){
            e.preventDefault();
            active_component.popover("hide");
        });
        //右弹form  确定控件：从弹出框中取值，赋值到component控件中
        $(popover).delegate(".btn-info", "click", function(e){
            e.preventDefault();//阻止元素发生默认的行为(例如,当点击提交按钮时阻止对表单的提交
            var inputs = $(popover).find("input");
            $.each(inputs, function(i,e){
                var attr_name = $(e).attr("id");//属性名称
                var attr_val = $("#"+attr_name).val();
                if(attr_name == 'orgvalue')
                {
                    $(leipiplugins).attr("productPropertyContents", attr_val);
                    active_component.find(".leipiplugins-orgvalue").text(attr_val);
                }
                active_component.popover("hide");
                LPB.genSource();//重置源代码
            });
        });

    }
})();
$(document).ready(function(){

});

function initLeiPiForm(){
    $("#navtab").delegate("#sourcetab", "click", function(e){
        LPB.genSource();
    });
    //鼠标向下点击
    $("form").delegate(".fix-component", "mousedown", function(md){
        $(".popover").remove();

        md.preventDefault();
        var tops = [];
        var mouseX = md.pageX;
        var mouseY = md.pageY;
        var $temp;//鼠标点击时的临时控件
        var timeout;
        var $this = $(this);
        var delays = {
            main: 0,
            form: 120
        }
        var type;

        if($this.parent().parent().parent().parent().attr("id") === "components"){
            type = "main";//表单外原始控件
        } else {
            type = "form";//表单内摆放好的控件
        }

        var delayed = setTimeout(function(){
            if(type === "main"){

                //leipiplugins="text",找到plugin类型
                var pluginType =$this.attr("leipiplugins");

                //弹出框内容
                var template = $('#' + pluginType +'-template').html();

                //main原始区域，拷贝一份作为临时控件
                $temp = $("<form class='form-horizontal span6' id='temp'></form>").append( template );

            } else {
                if($this.attr("id") !== "legend"){
                    $temp = $("<form class='form-horizontal span6' id='temp'></form>").append( $this );
                }
            }

            //添加到页面
            $("body").append($temp);
            //设置弹出的临时控件的位置
            $temp.css({"position" : "absolute",
                "top"      : mouseY - ($temp.height()/2) + "px",
                "left"     : mouseX - ($temp.width()/2) + "px",
                "opacity"  : "0.9"}).show()

            var half_box_height = ($temp.height()/2);
            var half_box_width = ($temp.width()/2);
            var $target = $(".public-content-tab");
            var tar_pos = $target.position();
            var $target_component = $(".public-content-tab .fix-component");

            //鼠标移动
            $(document).delegate("body", "mousemove", function(mm){
                var mm_mouseX = mm.pageX;
                var mm_mouseY = mm.pageY;

                //鼠标移动时，修改$temp的位置
                $temp.css({"top"      : mm_mouseY - half_box_height + "px",
                    "left"      : mm_mouseX - half_box_width  + "px"});

                //位置与表单对比，如果在表单里面，进入这个逻辑
                if ( mm_mouseX > tar_pos.left &&
                    mm_mouseX < tar_pos.left + $target.width() + $temp.width()/2 &&
                    mm_mouseY > tar_pos.top &&
                    mm_mouseY < tar_pos.top + $target.height() + $temp.height()/2
                ){

                    $(".public-content-tab").css("background-color", "#fafdff");

                    //以下代码设置border，我们暂时不需要用到
                    //$target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});

                    //tops:排查插入到了谁的前面，检查x和y
                    tops = $.grep($target_component, function(e){
                        var yCheck =  ($(e).position().top -  mm_mouseY + half_box_height > 0 && $(e).attr("id") !== "legend");
                        var xCheck =  ($(e).position().left -  mm_mouseX + half_box_width > 0 && $(e).attr("id") !== "legend");
                        return yCheck && xCheck ;
                    });
                    if (tops.length > 0){
                        //$(tops[0]).css("border-top", "1px solid #22aaff");
                    } else{
                        if($target_component.length > 0){
                            //$($target_component[$target_component.length - 1]).css("border-bottom", "1px solid #22aaff");
                        }
                    }
                } else{
                    $(".public-content-tab").css("background-color", "#fff");
                    //$target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
                    $target.css("background-color", "#fff");
                }
            });

            $("body").delegate("#temp", "mouseup", function(mu){
                mu.preventDefault();

                var mu_mouseX = mu.pageX;
                var mu_mouseY = mu.pageY;
                var tar_pos = $target.position();

                //$(".public-content-tab .fix-component").css({"border-top" : "1px solid white", "border-bottom" : "none"});

                // acting only if mouse is in right place
                if (mu_mouseX + half_box_width > tar_pos.left &&
                    mu_mouseX - half_box_width < tar_pos.left + $target.width() &&
                    mu_mouseY + half_box_height > tar_pos.top &&
                    mu_mouseY - half_box_height < tar_pos.top + $target.height()
                ){
                    //清除移动中的样式
                    $temp.attr("style", null);
                    // where to add
                    if(tops.length > 0){
                        //发现在tops的前面，插入到tops前面
                        $($temp.html()).insertBefore(tops[0]);
                    } else {
//            $(".public-content-tab fieldset").append($temp.append("\n\n\ \ \ \ ").html());
                        //直接插入到最后
                        $(".public-content-tab fieldset").append($temp.html());
                    }
                } else {
                    // no add
                    //$(".public-content-tab .fix-component").css({"border-top" : "1px solid white", "border-bottom" : "none"});
                    tops = [];
                }

                //clean up & add popover
                $target.css("background-color", "#fff");
                $(document).undelegate("body", "mousemove");
                $("body").undelegate("#temp","mouseup");

                //添加结束，激活targe里面component的popover事件
                $(".public-content-tab .fix-component").popover({trigger: "manual"});
                //删除临时控件
                $temp.remove();
                LPB.genSource();
            });
        }, delays[type]);

        $(document).mouseup(function () {
            clearInterval(delayed);
            return false;
        });
        $(this).mouseout(function () {
            clearInterval(delayed);
            return false;
        });
    });

    //activate legend popover,初始化激活popover事件
    //$(".public-content-tab .fix-component").popover({trigger: "manual"});

    //popover on click event
    //$(".public-content-tab").delegate(".fix-component", "click", function(e){
    $(".public-content-tab").delegate('.fix-component','click',function(e){
        e.preventDefault();
        $(".public-content-tab .fix-component").popover({trigger: "click"});
        var active_component = $(this);

        //class="leipiplugins",找到输入组件
        var leipiplugins = active_component.find(".leipiplugins");

        //leipiplugins="text",找到plugin类型
        var pluginType =$(leipiplugins).attr("leipiplugins");

        //弹出框内容
        var popcontent = $('#' + pluginType +'-popcontent').html();

        //根据type动态去获取html模板赋值进去，不用在content中存
        active_component.attr('data-content' , popcontent );

        active_component.popover("show");

        //exec plugins
        if(typeof(LPB.plugins[pluginType]) =='function')
        {
            try{
                LPB.plugins[pluginType](active_component,leipiplugins);
            }catch ( e ) {
                alert('控件异常，请到 [雷劈网] 反馈或寻求帮助！');
            }
        }else
        {
            alert("控件有误或不存在，请与我们联系！");
        }

    });
}
initLeiPiForm();